﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
using AutoMapper;
using CashFlow.Entities;
using CashFlow.Common;

namespace CashFlow.AzureRepository
{
	public class BillAzure : TableServiceEntity
	{
		public string Id { get; set; }
		public DateTime FirstDate { get; set; }
		public DateTime? LastDate { get; set; }
		public DateTime NextDate { get; set; }
		public double Amount { get; set; }
		public int NumberOfPayments { get; set; }
		public string TenantId { get; set; }
		public string AccountId { get; set; }
		public string PayeeName { get; set; }
		public string PayeeId { get; set; }
		public string Details { get; set; }
		public string RecurrenceId { get; set; }

		#region Constructors
		static BillAzure()
		{
			Mapper.CreateMap<Bill, BillAzure>().
				ForMember(dest => dest.PartitionKey, 	opt => opt.MapFrom(src => src.Tenant.Id)).
				ForMember(dest => dest.RowKey,				opt => opt.MapFrom(src => src.Id)).
				ForMember(dest => dest.TenantId,			opt => opt.MapFrom(src => src.Tenant.Id)).
				ForMember(dest => dest.AccountId,			opt => opt.MapFrom(src => src.Account.Id)).
				ForMember(dest => dest.RecurrenceId,	opt => opt.MapFrom(src => src.Recurrence.Id));

			Mapper.CreateMap<BillAzure, Bill>().
				ForMember(dest => dest.Tenant,			opt => opt.MapFrom(src => new Tenant { Id = src.TenantId })).
				ForMember(dest => dest.Account,			opt => opt.MapFrom(src => new Account { Id = src.AccountId })).
				ForMember(dest => dest.Payee,				opt => opt.MapFrom(src => new Payee { Id = src.PayeeId })).
				ForMember(dest => dest.Recurrence,	opt => opt.MapFrom(src => RecurrenceBase.GetNew(src.RecurrenceId)));
		}

		public BillAzure()
		{
		}
		#endregion

		#region Mappers
		public static explicit operator BillAzure(Bill entity)
		{
			if (string.IsNullOrEmpty(entity.Id))
				entity.Id = KeyGenerator.NewGuidBased();
			var model = Mapper.Map<Bill, BillAzure>(entity);
			return model;
		}

		public static explicit operator Bill(BillAzure model)
		{
			var entity = Mapper.Map<BillAzure, Bill>(model);

			return entity;
		}
		#endregion

		public BillAzure Clone()
		{
			var clone = new BillAzure { 
				PartitionKey = this.PartitionKey, 
				RowKey = this.RowKey,
				TenantId = this.TenantId,
				Id = this.Id,
				AccountId = this.AccountId,
				PayeeId = this.PayeeId,
				PayeeName = this.PayeeName,
				RecurrenceId = this.RecurrenceId,
				Amount = this.Amount,
				Details = this.Details,
				FirstDate = this.FirstDate,
				LastDate = this.LastDate, 
				NextDate = this.NextDate,
				NumberOfPayments = this.NumberOfPayments
			};
			return clone;
		}
	}
}
